package com.cnr.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cnr.model.Credentials;
import com.cnr.model.Posts;
import com.cnr.util.ManagePosts;

@Controller
@RequestMapping("/posts")
public class PostsController {

	private final Logger logger = Logger.getLogger(PostsController.class);
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String listPosts(HttpSession session, Model model) {
		List<Posts> posts = null;
		ManagePosts mp = new ManagePosts();
		Credentials user = (Credentials)session.getAttribute("user");
		if(user == null){
			logger.error("user could not be retrieved from session");
		}
		posts = mp.getPostsOfUser(user);
		if(posts == null || posts.isEmpty()){
			posts = mp.getPosts();
		}
		model.addAttribute("user", user);
		model.addAttribute("posts", posts);

		return "view/posts";
	}

}
